package net.youpo.Market.Util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.StatFs;
import android.util.Log;

public class Tools {
	private final static double MB = 1024;// KB换算成MB

	public static void saveBmpToSd(Bitmap bm, String fileName) {
		if (bm == null) {
			Log.w(ConstantsTable.LOG_TAG, " trying to savenull bitmap");
			return;
		}

		// 判断sdcard上的空间
		if (freeSpaceOnSd() < 1) {// sd剩余空间大于1M
			Log.w(ConstantsTable.LOG_TAG, "Low free space onsd, do not cache");
			return;
		}

		checkDirectory();
		File file = new File(ConstantsTable.CACHE_PATH + "/" + fileName);
		try {
			file.createNewFile();
			OutputStream outStream = new FileOutputStream(file);
			bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
			outStream.flush();
			outStream.close();
			Log.i(ConstantsTable.LOG_TAG, "Image saved tosd");
		} catch (FileNotFoundException e) {
			Log.w(ConstantsTable.LOG_TAG, "FileNotFoundException");
		} catch (IOException e) {
			Log.w(ConstantsTable.LOG_TAG, "IOException");
		}
	}

	/**
	 * 从缓存中获取图片
	 */
	public static Bitmap getBitmapFromCache(String filePath) {
		Bitmap bitmap = BitmapFactory.decodeFile(filePath);
		return bitmap;
	}

	/**
	 * 计算sdcard上的剩余空间
	 * 
	 * @return
	 */
	private static int freeSpaceOnSd() {
		StatFs stat = new StatFs(Environment.getExternalStorageDirectory()
				.getPath());
		double sdFreeMB = ((double) stat.getAvailableBlocks() * (double) stat
				.getBlockSize()) / MB;
		return (int) sdFreeMB;
	}

	/**
	 * 检查缓存文件夹是否创建
	 */
	private static void checkDirectory() {
		File directoryFile = new File(ConstantsTable.CACHE_PATH);
		if (!directoryFile.exists()) {
			directoryFile.mkdirs();
		}
	}
}
